package com.lcifn.middleware.rpc.transport.coder;

import com.lcifn.middleware.rpc.transport.command.Header;
import com.lcifn.middleware.rpc.transport.command.ResponseHeader;
import io.netty.buffer.ByteBuf;

import java.nio.charset.StandardCharsets;

/**
 * 服务端响应编码
 * @author lichao
 * @date 2021/2/1 16:32
 */
public class ServerResponseEncoder extends CommandEncoder {

    @Override
    protected void encodeHeader(Header header, ByteBuf byteBuf) {
        super.encodeHeader(header, byteBuf);
        if(header instanceof ResponseHeader) {
            ResponseHeader responseHeader = (ResponseHeader) header;
            byteBuf.writeInt(responseHeader.getCode());
            int errorLength = header.length() - (Integer.BYTES * 5);
            byteBuf.writeInt(errorLength);
            byteBuf.writeBytes(responseHeader.getError() == null ? new byte[0]: responseHeader.getError().getBytes(StandardCharsets.UTF_8));
        } else {
            throw new RuntimeException(String.format("Invalid header type: %s!", header.getClass().getCanonicalName()));
        }
    }
}
